﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Globalization;
using System.ServiceModel;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;
using System.Reflection;
using System.Xml;
using Microsoft.SharePoint.Publishing;

namespace hzWeb
{
   public static class Helper
    {
        public static string CrateSiteByTemplate(string templateName, string url, string title, SPSite site)
        {            
            var template = GetSiteTemplateByName(templateName, site);
            SPWeb web = site.RootWeb.Webs.Add(url, title, title,(uint) CultureInfo.CurrentCulture.LCID, template, false, false);
            web.Update();         
            AddColumnToMeetingRecords(web);
            if (PublishingWeb.IsPublishingWeb(web))
            {
               PublishingWeb publishWeb = PublishingWeb.GetPublishingWeb(web);
               publishWeb.IncludePagesInNavigation = false;
               publishWeb.IncludeSubSitesInNavigation = false;
               publishWeb.IncludeInCurrentNavigation = false;
               publishWeb.IncludeInGlobalNavigation = false;
               publishWeb.Navigation.GlobalIncludePages = false;
               publishWeb.Navigation.CurrentIncludePages = false;
               publishWeb.Web.AllowUnsafeUpdates = true;
               publishWeb.Update();
            }

            return web.Url;
        }

        public static void RemoveSite(string url, SPSite site)
        {
            url = url.Replace(site.Url, "");
            using (SPWeb web = site.OpenWeb(url))
            {
                if (web.Exists)
                {
                    web.Delete();
                    web.Update();
                }
            }
        }

        public static void CreateSite(string url, SPSite site, string template)
        {
            url = url.Replace(site.Url, "");
            using (SPWeb web = site.OpenWeb(url))
            {
                if (web.Exists)
                {
                    web.Delete();
                    web.Update();
                }
            }
        }

        public static MeetingRoomServiceClient GetMeetingRoomServiceClient(string serviceUrl)
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            // I think most (or all) of these are defaults--I just copied them from app.config:
            binding.SendTimeout = TimeSpan.FromMinutes(1);
            binding.OpenTimeout = TimeSpan.FromMinutes(1);
            binding.CloseTimeout = TimeSpan.FromMinutes(1);
            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.MessageEncoding = WSMessageEncoding.Text;
            binding.TextEncoding = System.Text.Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;

            return new MeetingRoomServiceClient(binding, new EndpointAddress(serviceUrl));
        }

        public static ChatRoomServiceClient GetChatRoomServiceClient(string serviceUrl)
        {
            BasicHttpBinding binding = new BasicHttpBinding();
            // I think most (or all) of these are defaults--I just copied them from app.config:
            binding.SendTimeout = TimeSpan.FromMinutes(1);
            binding.OpenTimeout = TimeSpan.FromMinutes(1);
            binding.CloseTimeout = TimeSpan.FromMinutes(1);
            binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
            binding.AllowCookies = false;
            binding.BypassProxyOnLocal = false;
            binding.MessageEncoding = WSMessageEncoding.Text;
            binding.TextEncoding = System.Text.Encoding.UTF8;
            binding.TransferMode = TransferMode.Buffered;
            binding.UseDefaultWebProxy = true;

            return new ChatRoomServiceClient(binding, new EndpointAddress(serviceUrl));

        }

        private static SPWebTemplate GetSiteTemplateByName(string templateName, SPSite site)
        {
            SPWebTemplateCollection templates = site.GetWebTemplates((uint)CultureInfo.CurrentCulture.LCID);
            return templates[templateName];
        }

        private static void AddColumnToMeetingRecords(SPWeb web)
        {
            // MeetingRecords
            web.AllowUnsafeUpdates = true;

            SPList list = web.Lists["MeetingRecords"];

            var titleField = list.Fields[Helper.GetTitle(web)];
            titleField.Hidden = true;
            titleField.Update();
            /* add the new fields to the list */
         
            list.Title = "会议记录";

            // list.ContentTypes["Audio"].Fields[0].sh    
             
            /* finally update list */
            list.Update();

            web.AllowUnsafeUpdates = false;
        }

        // page url: pages/default.aspx
        // list name: Documents
        // templateViewName: All Documents
        // fields : new string[] { "DocIcon", "LinkFilename", "Author", "Created" }
        public static void UpdateListViewWebPart(SPWeb web, string pageUrl,string[] fields, string listName, string templateViewName)
        {
            SPLimitedWebPartManager limitedWebPartManager = null;
            // web.Site.WebApplication.FormDigestSettings.Enabled = false; 
            try
            {
                // assume that you have a limitedWebPartManager variable containing an
                web.GetFile(pageUrl).CheckOut();
                limitedWebPartManager = web.GetLimitedWebPartManager(pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                // also assume that you have a list variable containing a reference to the
                SPList list = web.Lists[listName];

                foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in limitedWebPartManager.WebParts)
                {
                    // check to see if the type of the web part is ListViewWebPart, and if so, check if the title matches our guy.
                    if (webPart is XsltListViewWebPart)
                    {
                        // cast the web part to a ListViewWebPart so we can start to tweak its properties
                        var listViewWebPart = webPart as XsltListViewWebPart;

                        listViewWebPart.Toolbar = "ShowToolbar";

                        // here is some of the magic.  the web part now has its ViewGuid property populated which
                        // contains the Guid of the hidden view.  we get a reference to it here.
                        var view = list.Views[new Guid(listViewWebPart.ViewGuid)];

                        // here we grab a reference to a template view.  this may be the default view of the list,
                        // or maybe you have another view that you created that you want to use.  you don't have to
                        // do this, but in this scenario i wanted to copy the filter and sort settings from an existing view.
                        var templateView = list.Views[templateViewName];

                        // now we drop all of the view fields in the hidden view
                        view.ViewFields.DeleteAll();                   
                        Array.ForEach(fields, f => view.ViewFields.Add(f));
                        view.Toolbar = "ShowToolbar";

                        // here we copy the Query straight from the templateView.  if you didn't have a templateView you could always
                        // just create an SPQuery instance and assign it to the view.Query property.  no points will be taken off for doing that.
                        view.Query = templateView.Query;

                        view.GetType().InvokeMember("EnsureFullBlownXmlDocument", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, view, null, System.Globalization.CultureInfo.CurrentCulture);

                        PropertyInfo nodeProp = view.GetType().GetProperty("Node", BindingFlags.NonPublic | BindingFlags.Instance);
                        XmlNode node = nodeProp.GetValue(view, null) as XmlNode;
                        // Get the toolbar node from the XML of the view used in the web part
                        XmlNode toolbarNode = node.SelectSingleNode("Toolbar");
                        toolbarNode.Attributes["Type"].Value = "ShowToolbar";
                        // update our hidden view, and bask in the awesomeness of our customized ListViewWebPart
                        view.Update();
                        limitedWebPartManager.SaveChanges(listViewWebPart);
                    }
                }

                web.GetFile(pageUrl).CheckIn("system update");
                web.GetFile(pageUrl).Publish("system update");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                // web.Site.WebApplication.FormDigestSettings.Enabled = true;
                // do some fun cleanup of disposable items.  if you are wondering about the .Web.Dispose() bit look for my
                // blog article on the memory leaks in the SPLimitedWebPartManager.
                if (limitedWebPartManager != null)
                {
                    if (limitedWebPartManager.Web != null)
                    {
                        limitedWebPartManager.Web.Dispose();
                    }

                    limitedWebPartManager.Dispose();
                }                
            }
        }

        public static SPRoleDefinition GetRoleDefinition(SPRoleDefinitionCollection roleCollection, string roleName)
        {
            // Full Control
            // Helper.GetRoleDefinition(roleDefinitions,"Full Control")
            SPRoleDefinition roleDefinition = null;
            switch (roleName)
            {
                case "Full Control":
                    roleDefinition = GetRole(roleCollection, "Full Control") == null ? GetRole(roleCollection, "完全控制") : GetRole(roleCollection, "Full Control");
                    break;
                case "contribute":
                    roleDefinition = GetRole(roleCollection, "contribute") == null ? GetRole(roleCollection, "参与讨论") : GetRole(roleCollection, "contribute");
                    break;
                case "Contribute":
                    roleDefinition = GetRole(roleCollection, "contribute") == null ? GetRole(roleCollection, "参与讨论") : GetRole(roleCollection, "contribute");
                    break;
                case "Read":
                    roleDefinition = GetRole(roleCollection, "Read") == null ? GetRole(roleCollection, "读取") : GetRole(roleCollection, "Read");
                    break;
                case "read":
                    roleDefinition = GetRole(roleCollection, "Read") == null ? GetRole(roleCollection, "读取") : GetRole(roleCollection, "Read");
                    break;
            }

            return roleDefinition;
        }

       static SPRoleDefinition GetRole(SPRoleDefinitionCollection roleCollection, string roleName)
        {
            SPRoleDefinition roleDefinition = null;
            foreach (SPRoleDefinition role in roleCollection)
            {
                if (role.Name == roleName)
                {
                    roleDefinition = role;
                    break;
                }
            }

            return roleDefinition;
        }

       
       public static string GetTitle(SPWeb web)
       {
           if (web.Language == 2052)
           {
               return "标题";
           }
           else
           {
               return "Title";
           }
       }

       public static void WriteLog(string message)
       {
           Microsoft.Office.Server.Diagnostics.PortalLog.LogString("hzWebLogMessage:"+message);
           
       }
    }
}
